package top.xchch.tool.cipher.atguigu;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import java.security.*;

public class SignatureDemo09 {

    public static void main(String[] args) throws Exception {
        String algorithm = "RSA";
        String keyDir = "./src/main/resources/key/";
        String aPubPath = keyDir + "a.pub";
        String aPriPath = keyDir + "a.pri";
        PrivateKey privateKey = KeyGenerate08.getPrivateKey(aPriPath, algorithm);
        PublicKey publicKey = KeyGenerate08.getPublicKey(aPubPath, algorithm);

        // 获取数字签名
        String input = "123";
        String signature = getSignature(input, "sha256withrsa", privateKey);
        System.out.println(signature);
        
        // 校验签名
        boolean b = verifySignature(input, "sha256withrsa", publicKey, signature);
        System.out.println(b);
    }

    /**
     *
     * @param input 原文
     * @param signaturealgorithm 数字签名算法
     * @param publicKey 私钥key
     * @param signaturedData 签名密文
     * @return
     */
    private static boolean verifySignature(String input, String signaturealgorithm,
            PublicKey publicKey, String signaturedData) throws Exception {
        // 获取签名对象
        Signature signature = Signature.getInstance(signaturealgorithm);
        // 初始化签名
        signature.initVerify(publicKey);
        // 传入原文
        signature.update(input.getBytes());
        return signature.verify(Base64.decode(signaturedData));
    }

    /**
     * 生成数字签名
     * @param input 原文
     * @param signaturealgorithm 数字签名算法
     * @param privateKey 私钥key
     * @return
     */
    private static String getSignature(String input, String signaturealgorithm,
            PrivateKey privateKey) throws Exception {
        // 获取签名对象
        Signature signature = Signature.getInstance(signaturealgorithm);
        // 初始化签名
        signature.initSign(privateKey);
        // 传入原文
        signature.update(input.getBytes());
        // 开始签名
        byte[] sign = signature.sign();
        return Base64.encode(sign);
    }
}
